package org.example.myleet.p1592;

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public String reorderSpaces(String text) {
        StringBuilder word = new StringBuilder();
        int spaceCount = 0;
        List<String> words = new ArrayList<>();
        for (int i = 0; i < text.length(); ++i) {
            char c = text.charAt(i);
            if (c == ' ') {
                ++spaceCount;
                if (word.length() > 0) {
                    words.add(word.toString());
                    word.delete(0, word.length());
                }
            } else {
                word.append(c);
            }
        }
        if (word.length() > 0) {
            words.add(word.toString());
            word.delete(0, word.length());
        }
        int intervalSpaceCount = words.size() > 1 ? spaceCount / (words.size() - 1) : 0;
        int remain = spaceCount - intervalSpaceCount * (words.size() - 1);
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < words.size() - 1; ++i) {
            res.append(words.get(i));
            for (int j = 0; j < intervalSpaceCount; ++j) {
                res.append(' ');
            }
        }
        res.append(words.get(words.size() - 1));
        for (int j = 0; j < remain; ++j) {
            res.append(' ');
        }
        return res.toString();
    }
}
